package com.yuwen.yuwenRPC.bootstrap;

/**
 * @ClassNameProviderBootstrap
 * @Description TODO
 * @Author钰玟
 * @Date2025/4/6 下午2:27
 * @Version 1.0
 **/

import com.yuwen.RpcApplication;
import com.yuwen.yuwenRPC.config.RegistryConfig;
import com.yuwen.yuwenRPC.config.RpcConfig;
import com.yuwen.yuwenRPC.model.ServiceMetaInfo;
import com.yuwen.yuwenRPC.model.ServiceRegistryInfo;
import com.yuwen.yuwenRPC.registry.LocalRegistry;
import com.yuwen.yuwenRPC.registry.Registry;
import com.yuwen.yuwenRPC.registry.RegistryFactory;
import com.yuwen.yuwenRPC.server.tcp.VertxTcpServer;

import java.util.List;

import static com.yuwen.yuwenRPC.constant.RpcConstant.DEFAULT_SERVICE_VERSION;
import static com.yuwen.yuwenRPC.registry.LocalRegistry.registry;

/**
 * 提供者服务启动机制
 */
public class ProviderBootstrap {


    /**
     * 初始化
     */
    public static void init (List<ServiceRegistryInfo<?>> serviceRegistryInfoList) {
        /**
         * rpc框架初始化 （配置和注册中心）
         */
        RpcApplication.init();
        /**
         * 全局配置
         */
        RpcConfig rpcConfig = RpcApplication.getRpcConfig();
        for (ServiceRegistryInfo<?> serviceRegistryInfo : serviceRegistryInfoList) {
            String serviceName = serviceRegistryInfo.getServiceName();
            /**
             * 本地注册
             */
            LocalRegistry.registry(serviceName,serviceRegistryInfo.getServiceImpl());

            /**
             * 注册服务至注册服务中心
             */
            RegistryConfig registryConfig = rpcConfig.getRegistryConfig();
            Registry registry = RegistryFactory.getRegistry(registryConfig.getRegistryType());
            /**
             * 构建服务元信息
             */
            ServiceMetaInfo serviceMetaInfo = new ServiceMetaInfo();
            serviceMetaInfo.setServiceName(serviceName);
            serviceMetaInfo.setServiceHost(rpcConfig.getHost());
            serviceMetaInfo.setServicePort(rpcConfig.getPort());
            try {
                /**
                 * 注册至注册中心
                 */
                registry.register(serviceMetaInfo);
            } catch (Exception e) {
                throw new RuntimeException(serviceName+"注册服务失败",e);
            }
        }
        //启动tcp服务
        VertxTcpServer vertxTcpServer = new VertxTcpServer();
        vertxTcpServer.doStart(8080);
    }
}
